﻿using EFCore.BulkExtensions;
using LJ.DataAccess.EntityFrameworkCore.Internal;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LJ.DataAccess.EntityFrameworkCore.PostgreSQL.Internal;


public class EFPostgreSQLTransactionalProvider(IDbContextFactory<DataAccessDbContext> contextFactory) : EFTransactionalProviderBase(contextFactory)
{
    public override void Submit()
    {
        var bulkConfig = new BulkConfig
        {
            SetOutputIdentity = true,
            DoNotUpdateIfTimeStampChanged = true,
            SqlBulkCopyOptions = SqlBulkCopyOptions.CheckConstraints,
            UseTempDB = false
        };

        Context!.BulkSaveChanges(bulkConfig, null);

        if (bulkConfig.TimeStampInfo != null && bulkConfig.TimeStampInfo.NumberOfSkippedForUpdate > 0)
        {
            throw new DBConcurrencyException("Db Concurrency");
        }
    }

    public async override Task SubmitAsync(CancellationToken cancellationToken = default)
    {
        var bulkConfig = new BulkConfig
        {
            SetOutputIdentity = true,
            DoNotUpdateIfTimeStampChanged = true,
            SqlBulkCopyOptions = SqlBulkCopyOptions.CheckConstraints,
            UseTempDB = false
        };

        await Context!.BulkSaveChangesAsync(bulkConfig, null, cancellationToken);

        if (bulkConfig.TimeStampInfo != null && bulkConfig.TimeStampInfo.NumberOfSkippedForUpdate > 0)
        {
            throw new DBConcurrencyException("Db Concurrency");
        }
    }
}
